'use client';

import { useRef, useState } from 'react';
import { Button, message, Modal } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import type { ProColumns, ActionType } from '@ant-design/pro-components';
import { ProTable, ProForm, ProFormText, ProFormSelect } from '@ant-design/pro-components';
import { createUser, deleteUser, getUserList, updateUser } from '@/apis/admin/user';
import { User, UserRole, UserStatus } from '@/types/user';

const roleMap = {
  [UserRole.SUPER_ADMIN]: '超级管理员',
  [UserRole.ADMIN]: '管理员',
  [UserRole.USER]: '普通用户',
  [UserRole.VIP]: 'VIP',
};

const UserListPage = () => {
  const actionRef = useRef<ActionType>(null);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingUser, setEditingUser] = useState<User | null>(null);

  const handleCreate = async (values: User) => {
    try {
      await createUser(values);
      message.success('创建成功');
      actionRef.current?.reload();
      return true;
    } catch (error) {
      message.error('创建失败');
      return false;
    }
  };

  const handleUpdate = async (values: User) => {
    try {
      await updateUser({ ...editingUser, ...values });
      message.success('更新成功');
      actionRef.current?.reload();
      return true;
    } catch (error) {
      message.error('更新失败');
      return false;
    }
  };

  const handleDelete = async (id: string) => {
    Modal.confirm({
      title: '确定删除吗？',
      content: '删除后无法恢复',
      onOk: async () => {
        try {
          await deleteUser({ id });
          message.success('删除成功');
          actionRef.current?.reload();
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  const columns: ProColumns<User>[] = [
    { title: 'ID', dataIndex: 'id', key: 'id', width: 260 },
    { title: '用户名', dataIndex: 'username', key: 'username' },
    { title: '昵称', dataIndex: 'nickname', key: 'nickname' },
    { title: '邮箱', dataIndex: 'email', key: 'email' },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      valueEnum: {
        [UserRole.SUPER_ADMIN]: { text: roleMap[UserRole.SUPER_ADMIN] },
        [UserRole.ADMIN]: { text: roleMap[UserRole.ADMIN] },
        [UserRole.USER]: { text: roleMap[UserRole.USER] },
        [UserRole.VIP]: { text: roleMap[UserRole.VIP] },
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      valueEnum: {
        [UserStatus.ENABLED]: { text: '启用', status: 'Success' },
        [UserStatus.DISABLED]: { text: '禁用', status: 'Error' },
      },
    },
    { title: '创建时间', dataIndex: 'createdAt', key: 'createdAt', valueType: 'dateTime', hideInSearch: true },
    {
      title: '操作',
      key: 'action',
      hideInSearch: true,
      render: (_, record) => [
        <a
          key="edit"
          onClick={() => {
            setEditingUser(record);
            setIsModalVisible(true);
          }}
        >
          编辑
        </a>,
        <Button type='text' danger key="delete"  onClick={() => handleDelete(record.id)}>
          删除
        </Button>,
      ],
    },
  ];

  return (
    <>
      <ProTable<User>
        columns={columns}
        actionRef={actionRef}
        request={async (params) => {
          const res = await getUserList(params);
          return {
            data: res.data,
            total: res.total,
          };
        }}
        rowKey="id"
        search={{ labelWidth: 120 }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setEditingUser(null);
              setIsModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
      />
      <Modal
        title={editingUser ? '编辑用户' : '新建用户'}
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={null}
        destroyOnClose
      >
        <ProForm
          initialValues={editingUser || {}}
          onFinish={async (values) => {
            const success = editingUser ? await handleUpdate(values as User) : await handleCreate(values as User);
            if (success) {
              setIsModalVisible(false);
            }
          }}
        >
          <ProFormText name="username" label="用户名" rules={[{ required: true }]} />
          <ProFormText.Password name="password" label="密码" rules={[{ required: !editingUser }]} />
          <ProFormText name="nickname" label="昵称" />
          <ProFormText name="email" label="邮箱" />
          <ProFormSelect
            name="role"
            label="角色"
            options={Object.entries(roleMap).map(([value, label]) => ({ label, value: Number(value) }))}
          />
          <ProFormSelect
            name="status"
            label="状态"
            options={[
              { label: '启用', value: UserStatus.ENABLED },
              { label: '禁用', value: UserStatus.DISABLED },
            ]}
          />
        </ProForm>
      </Modal>
    </>
  );
};

export default UserListPage;